use dialoguer::{MultiSelect, theme::ColorfulTheme};
use walkdir::{DirEntry, WalkDir};

#[tokio::main]
async fn main() {
    // 先读取目标列表
    // 再选择清除
    let base_path: String = ".".to_string();
    let walk_iter = WalkDir::new(&base_path)
        .min_depth(1)
        .max_depth(3)
        .into_iter()
        .filter_map(|e| e.ok());

    let mut file_list: Vec<DirEntry> = Vec::new();

    for dir_entry in walk_iter {
        if is_rust_project(&dir_entry) {
            file_list.push(dir_entry);
        }
    }

    let selection: Vec<String> = file_list
        .iter()
        .map(|f| {
            let path_str = f.path().to_string_lossy().to_string();
            path_str
                .strip_prefix(&format!("{base_path}\\"))
                .unwrap_or(&path_str)
                .to_string()
        })
        .collect();

    let selected = match MultiSelect::with_theme(&ColorfulTheme::default())
        .with_prompt("请选择需要清理的项目")
        .items(&selection)
        .interact()
    {
        Ok(res) => res,
        Err(_) => {
            println!("没有可执行的项目");
            show_continue().await;
            std::process::exit(0)
        }
    };

    let clean_list: Vec<&DirEntry> = selected
        .iter()
        .filter_map(|index| file_list.iter().nth(*index))
        .collect();

    for dir_entry in clean_list {
        tokio::process::Command::new("cargo")
            .arg("clean")
            .current_dir(&dir_entry.path())
            .status()
            .await
            .unwrap();
    }
    show_continue().await;
}

fn is_rust_project(d: &DirEntry) -> bool {
    d.path()
        .to_str()
        .map(|p| {
            let has_cargo = std::path::Path::new(p).join("Cargo.toml").exists();
            let has_target = std::path::Path::new(p).join("target").exists();
            has_cargo && has_target
        })
        .unwrap_or(false)
}

async fn show_continue() {
    tokio::process::Command::new("cmd")
        .arg("/c")
        .arg("pause")
        .status()
        .await
        .unwrap();
}
